/**
 * 
 */
package com.somobile.json;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import com.google.gson.Gson;
import com.google.gson.JsonDeserializer;

/**
 * @author JatanP
 * 
 */
public class JSONHelper
{
	
	private JSONHelper()
	{
		
	}
	
	public static Object readObject(String url, Class c) throws IOException
	{
		return readObject(url, c,null);
	}
	
	public static Object readObject(String url, Class c,Map<Class,JsonDeserializer> typeAdapters) throws IOException
	{
		Gson gson = (typeAdapters==null?GSONHelper.getGson():GSONHelper.getGson(typeAdapters));

		
		URL u = new URL(url);
		
		HttpURLConnection conn = (HttpURLConnection) u.openConnection();
		
		conn.addRequestProperty("Accept-Encoding", "gzip");
		conn.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		InputStream is = conn.getInputStream();
		InputStreamReader reader = null;
		if("gzip".equals(conn.getHeaderField("Content-Encoding")))
		{
			reader = new InputStreamReader(new GZIPInputStream(is));
		}
		else
		{
			 reader = new InputStreamReader(is);
		}
		
	
		return gson.fromJson(reader, c);
	}


}
